function css2Style(contentNode) {
  const len = document.styleSheets.length;
  for (let sheetInd = 0; sheetInd < len; sheetInd++) {
    const cssRules = document.styleSheets[sheetInd].cssRules;
    for (let cssInd = 0; cssInd < cssRules.length; cssInd++) {
      const selectorText = cssRules[cssInd].selectorText;
      const size = cssRules[cssInd]?.styleMap?.size || 0;
      if (contentNode) break;
      const domList = contentNode.querySelectorAll(selectorText);
      for (let domInd = 0; domInd < domList.length; domInd++) {
        const dom = domList[domInd];
        for (let styleInd = 0; styleInd < size; styleInd++) {
          const styleName = cssRules[cssInd].style[styleInd];
          dom.style[styleName] = cssRules[cssInd].style[styleName];
        }
      }
    }
  }
  return contentNode;
}

function saveData(selector, fileName, callBack) {
  const mainEl = document.querySelector(selector);
  if (!mainEl) return '未找到该元素节点';
  const contentNode = mainEl.cloneNode(true);
  const data = wordExport(css2Style(contentNode));
  contentNode.style.maxWidth = window.innerWidth + 'px';
  downLoad(data, fileName, callBack);
}

function removeNotOutElment(contentNode, list = ['.not-out']) {
  for (const listItem of list) {
    const domList = contentNode.querySelectorAll(listItem);
    for (let i = 0; i < domList.length; i++) {
      domList[i].remove();
    }
  }
  return contentNode;
}

function rem2Px(html) {
  const rootSize = document.documentElement.style.fontSize;
  if (!rootSize) return html;
  const sizeNumber = parseInt(rootSize);
  html.replace(/(\d+)rem;/g, function (_, $1) {
    return $1 * sizeNumber + 'px;';
  });
  return html;
}

function wordExport(contentNode) {
  contentNode = removeNotOutElment(contentNode);
  const staticObj = {
    mhtml: {
      top:
        'Mime-Version: 1.0\nContent-Base: ' +
        location.href +
        '\nContent-Type: Multipart/related; boundary="NEXT.ITEM-BOUNDARY";type="text/html"\n\n--NEXT.ITEM-BOUNDARY\nContent-Type: text/html; charset="utf-8"\nContent-Location: ' +
        location.href +
        '\n\n<!DOCTYPE html>\n<html>\n_html_</html>',
      head: '<head>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n<style>\n_styles_\n</style>\n</head>\n',
      body: '<body>_body_</body>',
    },
  };
  const options = {
    maxWidth: 1000,
  };
  // Clone selected element before manipulating it
  const markup = contentNode.cloneNode(true);
  // Remove hidden elements from the output

  // Embed all images using Data URLs
  const images = Array();
  const img = markup.getElementsByTagName('img');
  for (let i = 0; i < img.length; i++) {
    let imgW = parseInt(img[i].style.width) || img[i].width;
    let imgH = parseInt(img[i].style.height) || img[i].height;
    // Calculate dimensions of output image
    const w = Math.min(imgW, options.maxWidth);
    const h = imgH * (w / imgW);
    try {
      // Create canvas for converting image to data URL
      const canvas = document.createElement('CANVAS');
      canvas.width = w;
      canvas.height = h;
      // Draw image to canvas
      const context = canvas.getContext('2d');
      context.drawImage(img[i], 0, 0, w, h);
      // Get data URL encoding of image
      const uri = canvas.toDataURL('image/png');
      img[i].setAttribute('src', uri);
      images[i] = {
        type: uri.substring(uri.indexOf(':') + 1, uri.indexOf(';')),
        encoding: uri.substring(uri.indexOf(';') + 1, uri.indexOf(',')),
        location: $(img[i]).attr('src'),
        data: uri.substring(uri.indexOf(',') + 1),
      };
    } catch (err) {
      console.warn(err);
    }
    img[i].width = w;
    img[i].height = h;
    img[i].align = img[i].style.float;
  }

  // Prepare bottom of mhtml file with image data
  let mhtmlBottom = '\n';
  for (let i = 0; i < images.length; i++) {
    mhtmlBottom += '--NEXT.ITEM-BOUNDARY\n';
    mhtmlBottom += 'Content-Location: ' + images[i].location + '\n';
    mhtmlBottom += 'Content-Type: ' + images[i].type + '\n';
    mhtmlBottom += 'Content-Transfer-Encoding: ' + images[i].encoding + '\n\n';
    mhtmlBottom += images[i].data + '\n\n';
  }
  mhtmlBottom += '--NEXT.ITEM-BOUNDARY--';
  // console.log('markup', markup.innerHTML);
  // Aggregate parts of the file together
  const showHtml = rem2Px(markup.innerHTML);
  const styles = '';
  const fileContent =
    staticObj.mhtml.top.replace(
      '_html_',
      staticObj.mhtml.head.replace('_styles_', styles) +
        staticObj.mhtml.body.replace('_body_', showHtml),
    ) + mhtmlBottom;
  // const fileContent = `<html>${showHtml}</html>`;
  // console.log('%c Line:114 🍕 fileContent', 'color:#f5ce50', fileContent);
  // Create a Blob with the file contents
  const blob = new Blob([fileContent], {
    type: 'application/msword;charset=utf-8',
  });
  return blob;
}
/* 
wps:kswps
docx:msword
*/
function downLoad(data, fileName, callBack) {
  // const blob = new Blob([data], { type: 'application/kswps' });
  const reader = new FileReader();
  reader.readAsDataURL(data);
  console.info(fileName);
  reader.onload = (e) => {
    const link = document.createElement('a');
    link.setAttribute('href', e.target.result);
    link.setAttribute('download', `${fileName}.doc`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };
}
//--------------------------------------另一种直接页面打印----------------------
// 导出函数
function exportFileByInerHTML(inerHTML, fileName) {
  let blob;
  try {
    //word文档为msword,docx为vnd,pdf文档为pdf,msexcel 为excel
    blob = new Blob([inerHTML], {
      type: 'application/msword;charset=utf-8',
    });
  } catch (e) {
    if (typeof console !== 'undefined') {
      this.$message.error('导出失败');
      console.log(e);
    }
  }
  let objectUrl = URL.createObjectURL(blob);
  let link = document.createElement('a');
  let fname = `${fileName}.doc`; //下载文件的名字
  link.href = objectUrl;
  link.setAttribute('download', fname);
  document.body.appendChild(link);
  link.click();
}

// todo设置表格样式 设置边框
function setTableStyle() {
  let tableDomList = document
    .querySelector('.table-designer-container')
    .getElementsByTagName('table');

  // 去除element的覆盖层
  this.isPrintToPdfFlag = true;
  let headRightTh = tableDomList[0]
    .getElementsByTagName('tr')[0]
    .getElementsByTagName('th');
  // 添加表头最右侧的边框
  headRightTh[headRightTh.length - 2].style.borderRight = '1px solid #ABABAB';

  // 遍历两个table
  let tableLength = tableDomList.length;
  for (let i = 0; i < tableLength; i++) {
    tableDomList[i].setAttribute('border', '1');
    tableDomList[i].style.border = '#ffffff';
    let childTr = tableDomList[i].getElementsByTagName('tr');
    let childTrLength = childTr.length;
    // 第一个table是头部，没有td会报错
    if (i > 0) {
      for (let j = 0; j < childTrLength; j++) {
        let childTd = childTr[j].getElementsByTagName('td');
        let childTdLength = childTd.length;
        // 修改最后一个的边框值
        if (childTd[childTdLength - 1].style) {
          childTd[childTdLength - 1].style.borderRight = '1px solid #ABABAB';
        }

        for (let k = 0; k < childTdLength; k++) {
          childTd[k].style.padding = '8px 0'; //改变之后与element高度一致
          childTd[k].style.valign = 'center';
          childTd[k].style.align = 'center';
          childTd[k].style.textAlign = 'center';

          if (j == childTrLength - 1) {
            childTd[k].style.borderBottom = '1px solid #ABABAB';
          }
        }
      }
    } else {
      // 去除第一个table去除最右侧的空白th
      let childTr = tableDomList[i].getElementsByTagName('tr');
      let childTrLength = childTr.length;
      for (let i = 0; i < childTrLength; i++) {
        let lastTh = childTr[i].querySelector('.gutter');
        if (lastTh) {
          lastTh.parentNode.removeChild(lastTh);
        }
      }
    }
  }
}
// todo清除表格样式
function clearTableStyle() {
  let tableDomList = document
    .querySelector('.table-designer-container')
    .getElementsByTagName('table');

  // 去除第一个table表头最右侧的边框
  let headRightTh = tableDomList[0]
    .getElementsByTagName('tr')[0]
    .getElementsByTagName('th');
  headRightTh[headRightTh.length - 2].style.borderRight = 'none';

  //去除右侧和最底部的样式
  for (let i = 0; i < tableDomList.length; i++) {
    tableDomList[i].setAttribute('border', '0');
    tableDomList[i].style.border = 'none';
    let childTr = tableDomList[i].getElementsByTagName('tr');
    let childTrLength = childTr.length;
    // 第一个table是头部，没有td会报错
    if (i > 0) {
      for (let j = 0; j < childTrLength; j++) {
        let childTd = childTr[j].getElementsByTagName('td');
        let childTdLength = childTd.length;
        // 修改最后一个的边框值
        if (childTd[childTdLength - 1].style) {
          childTd[childTdLength - 1].style.borderRight = 'none';
        }
        for (let k = 0; k < childTdLength; k++) {
          if (j == childTrLength - 1) {
            childTd[k].style.borderBottom = 'none';
          }
        }
      }
    }
  }
}

export { css2Style, saveData, wordExport, downLoad, exportFileByInerHTML };
